package com.cloud.basic.Proxy;


import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;

/**
 * @program: basic
 * @description: cglib代理
 * @author: Cloud
 * @create: 2020/11/25 14:35:38
 */
public class CglibProxy implements MethodInterceptor {

    // 需要代理的对象
    private Object target;

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("cglib代理开始！");
        Object invoke = method.invoke(target,objects);
        System.out.println("cglib代理结束！");
        return invoke;
    }

    // 获取代理对象
    public Object getCglibProxy(Object o){
        // 为目标对象赋值
        this.target = o;
        Enhancer enhancer = new Enhancer();
        // 设置父类，因为是cglib通过父类来生成子类的
        enhancer.setSuperclass(o.getClass());
        // 回调
        enhancer.setCallback(this);
        // 创建代理对象
        Object result = enhancer.create();
        return result;
    }

    public static void main(String[] args) {
        CglibProxy cglibProxy = new CglibProxy();
        SysUserManager o1 = (SysUserManager)cglibProxy.getCglibProxy(new SysUserManagerImp());
        o1.addUser("李四","打篮球","医生");
    }
}
